<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'
import { MaterialListParam } from '@/api/material/type'
import { getListApi } from '@/api/material'
import { getSimpleListApi } from '@/api/materialCategory/index.ts'
import { Search, Refresh } from '@element-plus/icons-vue'
import TreeSelect from '@/components/TreeSelect/index.vue'

// ----------------------- 组件状态定义 -----------------------
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()

// 定义emit事件
const emit = defineEmits([
  'handleMaterialSelectionChange',
  'confirmMaterialSelect',
  'handleMaterialSelect'
])

// 添加表格引用
const tableRef = ref()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<MaterialListParam>({
  materialCode: undefined,
  materialName: undefined,
  categoryId: undefined,
  brand: undefined,
  manufacturer: undefined,
  page: 1,
  limit: 10,
})

// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.materialCode = undefined
  searchForm.materialName = undefined
  searchForm.categoryId = currentCategoryId.value || undefined
  searchForm.brand = undefined
  searchForm.manufacturer = undefined
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    let res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
      // 等待表格数据加载完成后设置选中状态
      setTimeout(() => {
        tableData.value.forEach((row: any) => {
          const isSelected = selectedMaterials.value.some(
              (material: any) => material.id === row.id
          )
          console.log("数据重置选中:"+isSelected)
          if (isSelected) {
            tableRef.value.toggleRowSelection(row, true)
          }
        })
      },300)
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// ----------------------- 左侧筛选树形数据处理 -----------------------
const currentCategoryId = ref<number>()

// 保存已经选择的物料
const selectedMaterials = ref<any[]>([])

interface TreeNode {
  id: string
  categoryName: string
  parentId: string
  children: TreeNode[]
}

const treeData = ref<TreeNode[]>([])

const getTreeData = async () => {
  try {
    const res = await getSimpleListApi()
    if (res?.data) {
      treeData.value = handleTree(res.data)
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

const handleTree = (data: TreeNode[]): TreeNode[] => {
  const map = new Map<string, TreeNode>()
  const result: TreeNode[] = []

  const rootNode: TreeNode = {
    id: '-1',
    categoryName: '全部分类',
    parentId: '',
    children: [],
  }

  data.forEach((item) => {
    map.set(item.id, { ...item, children: [] })
  })

  data.forEach((item) => {
    const node = map.get(item.id)!
    if (item.parentId === '0') {
      rootNode.children.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  result.push(rootNode)
  return result
}

const handleTreeNodeClick = async (data: any) => {
  if (data.id === '-1') {
    currentCategoryId.value = undefined
    searchForm.categoryId = undefined
  } else {
    currentCategoryId.value = data.id
    searchForm.categoryId = data.id
  }
  searchForm.page = 1
  searchForm.limit = 10
  searchForm.materialCode = undefined
  searchForm.materialName = undefined
  searchForm.brand = undefined
  searchForm.manufacturer = undefined
  await getTableData()
}

// 选择物料 selection：全部选中的数据     当前点击数据row
const handleSelect = (selection:[], row: any) => {
  console.log("组件选择物料数据："+selection);
  // 判断是选中还是取消
  const isSelected =  selection.some(item=>{
    return  item == row
  })
  if(isSelected) {  //勾选了则添加到已选数组中
    selectedMaterials.value.push(row)
  } else {
    selectedMaterials.value = selectedMaterials.value.filter(item=>{
      return item.id != row.id
    })
  }
  console.log("是否选择："+isSelected);
  console.log("已选数据："+selection.length);
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 全选
const handleSelectAll = (selection: any[]) => {
  // 判断是全选还是取消全选
  const isSelected = selection.length === tableData.value.length
  if (isSelected) {
    // 循环全选的数据判断这些数据中是否包含了之前就选择了的数据
    selection.forEach(item=>{
      const some = selectedMaterials.value.some((row: any) => row.id === item.id);
      if(!some) {
        selectedMaterials.value.push(item)
      }
    })
  } else {
    // 清空当前tableData中的已选数据
    selectedMaterials.value = selectedMaterials.value.filter((item: any) => {
      return !tableData.value.some((row: any) => row.id === item.id)
    })
  }
  emit('handleMaterialSelectionChange', selectedMaterials.value)
}

// 确认选择完毕
const confirmMaterial = () => {
  emit('confirmMaterialSelect')
}

// 关闭弹框
const closeDialog = () => {
  onClose()
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  dialog.height = 500
  dialog.width = 1200
  dialog.title = '选择物料'
  getTreeData()
  getTableData()
  nextTick(() => {
    tableHeight.value = 380
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = 380
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 暴露方法给父组件
defineExpose({
  onShow: (preSelectedMaterials = []) => {
    console.log("本次预选的数据:"+preSelectedMaterials.length);
    dialog.visible = true
    selectedMaterials.value= preSelectedMaterials
    // 如果有预选物料，设置表格的选中状态
    if (preSelectedMaterials && preSelectedMaterials.length > 0) {
      // 等待表格数据加载完成后设置选中状态
      nextTick(() => {
        setTimeout(() => {
          if (tableRef.value) {
            // 先清除所有选中状态
            tableRef.value.clearSelection()
            // 设置选中状态
            tableData.value.forEach((row: any) => {
              const isSelected = preSelectedMaterials.some(
                  (material: any) => material.id === row.id
              )
              if (isSelected) {
                tableRef.value.toggleRowSelection(row, true)
              }
            })
          }
        }, 300)
      })
    }
  },
  onClose,
})

// 接收父组件参数
const props = defineProps({
  multiple: {
    type: Boolean,
    default: true
  }
})

// 点击选择某一行，获取那行的数据
const handleRowClick = (row: any) => {
  if (!props.multiple) {
    emit('handleMaterialSelect', row)
    console.log("物料子传父："+row.materialName)
    closeDialog()
  }
}
</script>

<template>
  <sys-dialog :title="dialog.title"
              :width="dialog.width"
              :visible="dialog.visible"
              :height="dialog.height"
              @onClose="closeDialog"
              @on-confirm="confirmMaterial">
    <template #content>
      <div class="material-dialog-container">
        <el-row :gutter="10">
          <!-- 左侧树形菜单 -->
          <el-col :span="5">
            <TreeSelect :data="treeData"
                        :props="{
                  children: 'children',
                  label: 'categoryName'
                }"
                        placeholder="请输入分类名称"
                        @node-click="handleTreeNodeClick" />
          </el-col>
          <!-- 右侧内容区 -->
          <el-col :span="19">
            <!-- 查询表单区域 -->
            <el-card class="search-card">
              <el-form :inline="true"
                       :model="searchForm"
                       class="search-form">
                <el-form-item label="物料编码">
                  <el-input v-model="searchForm.materialCode"
                            placeholder="请输入物料编码" />
                </el-form-item>
                <el-form-item label="物料名称">
                  <el-input v-model="searchForm.materialName"
                            placeholder="请输入物料名称" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary"
                             @click="search">
                    <el-icon>
                      <Search />
                    </el-icon>
                    查询
                  </el-button>
                  <el-button @click="reset">
                    <el-icon>
                      <Refresh />
                    </el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 表格区域 -->
            <el-table v-loading="loading"
                      :data="tableData"
                      border
                      :height="tableHeight"
                      style="margin-top: 15px"
                      @select="handleSelect"
                      @select-all="handleSelectAll"
                      @row-click="handleRowClick"
                      ref="tableRef">
              <el-table-column v-if="multiple" type="selection" width="55" />
              <el-table-column prop="materialCode"
                               label="物料编码"
                               min-width="120" />
              <el-table-column prop="materialName"
                               label="物料名称"
                               min-width="150" />
              <el-table-column prop="categoryName"
                               label="物料类型"
                               min-width="120" />
              <el-table-column prop="unitName"
                               label="计量单位"
                               min-width="90" />
              <el-table-column prop="specification"
                               label="规格"
                               min-width="200" />
              <el-table-column prop="purchasePrice"
                               label="采购单价"
                               min-width="100" />
              <el-table-column prop="materialType" label="材质" min-width="100" />
              <el-table-column prop="unitWeight" label="米重(kg/m)" min-width="100" />
              <el-table-column prop="unitArea" label="面积(m²/m)" min-width="100" />
              <el-table-column prop="totalWeight" label="总重(kg/件)" min-width="100" />
              <el-table-column prop="thickness" label="厚度(mm)" min-width="100" />
              <el-table-column prop="length" label="高度" min-width="100" />
              <el-table-column prop="breadth" label="宽度" min-width="100" />
            </el-table>

            <!-- 分页 -->
            <el-pagination v-model:current-page="paginationData.currentPage"
                           v-model:page-size="paginationData.pageSize"
                           :page-sizes="[10, 20, 50]"
                           :total="paginationData.total"
                           layout="total, sizes, prev, pager, next"
                           class="pagination"
                           @size-change="getTableData"
                           @current-change="getTableData" />
          </el-col>
        </el-row>
      </div>
    </template>
  </sys-dialog>
</template>

<style scoped lang="scss">
.material-dialog-container {
  padding: 0 0px;
  box-sizing: border-box;
  height: 100%;
  overflow: hidden;
}

.el-pagination {
  margin-top: 10px;
  justify-content: flex-end;
}

.search-card {
  height: 65px;

  :deep(.el-card__body) {
    padding: 10px;
  }
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 10px;
  margin-bottom: 0;
}

:deep(.el-input) {
  width: 180px;
}
</style>
